/**
 * 处理children形式数据
 * @param data 需要处理的数据
 * @param formatter 处理器
 * @param childrenField children字段名
 * @returns {[]} 处理后的数据
 */
export function formatTreeData (data, formatter, childrenField = 'children') {
  const result = []
  data.forEach((d) => {
    const item = formatter(d)
    if (item !== false) {
      if (item[childrenField]?.length) {
        item[childrenField] = formatTreeData(
          item[childrenField],
          formatter,
          childrenField
        )
      }
      result.push(item)
    }
  })
  return result
}


/**
 * parentId形式数据转children形式
 * @param option
 * @returns {[]} 转换后的数据
 */
export function toTreeData (option) {
  const data = option.data
  const idField = option.idField || option.idKey || 'id'
  const parentIdField = option.parentIdField || option.pidKey || 'parentId'
  const childrenField = option.childrenField || option.childKey || 'children'
  const parentIdIsNull =
    typeof option.parentId === 'undefined' && typeof option.pid === 'undefined'
  const parentId = parentIdIsNull ? [] : option.parentId ?? option.pid
  const addParentIds = option.addParentIds ?? option.addPIds
  const parentIdsField =
    option.parentIdsField || option.parentsKey || 'parentIds'
  const parentIds = option.parentIds
  if (parentIdIsNull) {
    data.forEach((d) => {
      let flag = true
      for (let i = 0; i < data.length; i++) {
        if (d[parentIdField] === data[i][idField]) {
          flag = false
          break
        }
      }
      if (flag) {
        parentId.push(d[parentIdField])
      }
    })
  }

  const result = []
  data.forEach((d) => {
    if (d[idField] === d[parentIdField]) {
      throw new Error(
        [
          'data error: {',
          idField + ': ',
          JSON.stringify(d[idField]),
          parentIdField + ': ',
          JSON.stringify(d[parentIdField]),
          '}'
        ].join('')
      )
    }
    const isArr = Array.isArray(parentId)
    const isParent = isArr
      ? parentId.includes(d[parentIdField])
      : d[parentIdField] === parentId
    if (isParent) {
      const r = Object.assign({}, d)
      const children = toTreeData({
        data,
        idField,
        parentIdField,
        childrenField,
        parentId: d[idField],
        addParentIds,
        parentIdsField,
        parentIds: (parentIds ?? []).concat([d[idField]])
      })
      if (children.length > 0) {
        r[childrenField] = children
      }
      if (addParentIds) {
        r[parentIdsField] = parentIds ?? []
      }
      result.push(r)
    }
  })
  return result
}
